package com.hnu.highlynewapp.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.hnu.highlynewapp.exception.BizCodeEnum;
import com.hnu.highlynewapp.utils.OssUtil;
import com.hnu.highlynewapp.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

/**
 * @author kLjSumi
 * @Date 2021/1/3
 */
@Api(tags = "对象存储api管理")
@RestController
public class OssController {

    @Autowired
    private OssUtil ossUtil;

    /**
     * 单文件上传
     * @param file
     * @return
     */
    @ApiOperation("单文件上传")
    @PostMapping("upload/single")
    public R upload(@RequestParam("file") MultipartFile file) {
        String url = null;
        try {
            url = ossUtil.upload(file);
        } catch (IOException e) {
            return R.error(BizCodeEnum.UPLOAD_FAIL_EXCEPTION.getCode(), BizCodeEnum.UPLOAD_FAIL_EXCEPTION.getMessage());
        }
        Map<String,Object> map = new HashMap<>();
        map.put("url",url);
        return R.ok().put("data", map);
    }

    /**
     * 多文件上传
     * @param files
     * @return
     */
    @ApiOperation("多文件上传")
    @PostMapping("upload/multi")
    public R upload(@RequestParam("files") MultipartFile[] files) {
        List<String> urls = null;
        try {
            urls = ossUtil.upload(files);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String,Object> map = new HashMap<>();
        map.put("urls",urls);
        return R.ok().put("data",map);
    }

}
